package com.zenithmind.chat.service.impl;

import com.zenithmind.chat.pojo.dto.AiChatMessageDTO;
import com.zenithmind.chat.service.AiChatService;
import com.zenithmind.chat.service.AiChatStreamService;
import com.zenithmind.chat.exception.AiChatException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * AI对话流式服务实现类
 * 遵循单一职责原则，专门负责流式响应处理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiChatStreamServiceImpl implements AiChatStreamService {
    
    private final AiChatService aiChatService;
    
    // 线程池管理 - 遵循单一职责原则，由专门的服务管理
    private final ExecutorService sseExecutor = Executors.newCachedThreadPool(r -> {
        Thread thread = new Thread(r, "sse-stream-" + System.currentTimeMillis());
        thread.setDaemon(true);
        return thread;
    });
    
    @Override
    public SseEmitter sendMessageStream(AiChatMessageDTO messageDTO, String userId) {
        SseEmitter emitter = createSseEmitter();
        
        // 异步处理流式响应
        sseExecutor.submit(() -> {
            try {
                aiChatService.sendMessageStream(messageDTO, emitter, userId);
            } catch (AiChatException e) {
                log.error("AI聊天业务异常: {}", e.getMessage());
                handleSseError(emitter, e);
            } catch (Exception e) {
                log.error("流式消息处理失败", e);
                handleSseError(emitter, AiChatException.streamProcessingFailed(e.getMessage()));
            }
        });
        
        return emitter;
    }
    
    @Override
    public SseEmitter createSseEmitter() {
        SseEmitter emitter = new SseEmitter(30000L); // 30秒超时
        
        emitter.onTimeout(() -> handleSseTimeout(emitter));
        emitter.onError(throwable -> handleSseError(emitter, throwable));
        emitter.onCompletion(() -> log.debug("SSE连接完成"));
        
        return emitter;
    }
    
    @Override
    public void handleSseTimeout(SseEmitter emitter) {
        log.warn("SSE连接超时");
        try {
            emitter.send(SseEmitter.event()
                .name("error")
                .data("连接超时"));
            emitter.complete();
        } catch (Exception e) {
            log.error("处理SSE超时失败", e);
        }
    }
    
    @Override
    public void handleSseError(SseEmitter emitter, Throwable throwable) {
        log.error("SSE连接错误", throwable);
        try {
            emitter.send(SseEmitter.event()
                .name("error")
                .data("连接错误: " + throwable.getMessage()));
            emitter.complete();
        } catch (Exception e) {
            log.error("处理SSE错误失败", e);
        }
    }
    
    @Override
    public void completeSse(SseEmitter emitter) {
        try {
            emitter.complete();
            log.debug("SSE连接正常完成");
        } catch (Exception e) {
            log.error("完成SSE连接失败", e);
        }
    }
}
